package org.m2acsi.control;

import java.io.IOException;
import java.io.Serializable;
import javax.annotation.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.m2acsi.boundary.TaskEJB;
import org.m2acsi.boundary.UserEJB;
import org.m2acsi.entities.User;

@Named
@RequestScoped
@ManagedBean
public class BaseBean implements Serializable {

    @Inject
    UserEJB userEjb;

    @Inject
    TaskEJB taskEjb;

    private User authenticatedUser;

    public User getAuthenticatedUser() {
        if (authenticatedUser == null) {
            authenticatedUser = userEjb.findUser(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser());
        }
        return authenticatedUser;
    }

    public void setAuthenticatedUser(User authenticatedUser) {
        this.authenticatedUser = authenticatedUser;
    }

    public String getUserRole() {
        return getAuthenticatedUser() == null ? "" : authenticatedUser.getRoleName().name();
    }

    /**
     * @param URL The page url, starting with <code>/faces/...</code>
     */
    protected void redirect(String URL) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect(new StringBuilder().append(FacesContext.getCurrentInstance().getExternalContext().getApplicationContextPath()).append(URL).toString());
        } catch (IOException ex) {
        }
    }

    protected void redirectWithMessage(String URL, String message) {
        String arg = "?";
        if (URL.indexOf("?") != -1) {
            arg = "&";
        }
        redirect(new StringBuilder().append(URL).append(arg).append("ui-message=").append(message.replace(" ", "%20")).toString());
    }

    /**
     * @param duration Display time in ms
     */
    protected void redirectWithMessage(String URL, String message, int duration) {
        String arg = "?";
        if (URL.indexOf("?") != -1) {
            arg = "&";
        }
        redirect(new StringBuilder().append(URL).append(arg).append("ui-message=").append(message.replace(" ", "%20")).append("&ui-message-duration=").append(duration).toString());
    }

    public void hackRedirect() {
        redirect("/faces/logout.xhtml?reason=hack");
    }

    public void hackRedirect(String phrase) {
        redirect(new StringBuilder().append("/faces/logout.xhtml?reason=hack&phrase=").append(phrase.replace(" ", "%20")).toString());
    }
}
